<template>
  <a-modal
    title="分配权限"
    :destroy-on-close="true"
    :mask-closable="false"
    :visible="visible"
    :confirm-loading="loading"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-tree
      v-if="isShowTree"
      v-model:checkedKeys="checkedKeys"
      :tree-data="treeDataSource"
      :default-expand-all="true"
      :show-line="true"
      checkable
    >
    </a-tree>
  </a-modal>
</template>

<script name="SystemRoleMenu" lang="ts" setup>
import { getMenuByRoleId, getTree } from "@/api/system/menu";
import { formatTreeSelect } from "@/utils/format";
import { updateRoleMenu } from "@/api/system/role";
import { defineExpose } from "vue";

const visible = ref(false);
const roleId = ref(0);
const loading = ref(false);
const isShowTree = ref(false);
const treeDataSource = ref<any>([]);
const checkedKeys = ref<string[]>([]);

const getMenu = () => {
  loading.value = true;
  checkedKeys.value = [];
  getTree()
    .then(response => {
      treeDataSource.value = formatTreeSelect(response.data);
      if (response.data.length > 0) {
        getMenuByRoleId(roleId.value)
          .then(response => {
            const resData = response.data as Array<any>;
            resData.forEach(item => {
              checkedKeys.value.push(item.menuId);
            });
            isShowTree.value = true;
          })
          .finally(() => {
            loading.value = false;
          });
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const show = (id: number) => {
  visible.value = true;
  roleId.value = id;
  getMenu();
};

const handleClose = () => {
  visible.value = false;
};

const handleSubmit = () => {
  loading.value = true;
  updateRoleMenu({
    roleId: roleId.value,
    menuIds: checkedKeys.value
  })
    .then(() => {
      antdMessage.success("编辑成功");
      handleClose();
    })
    .finally(() => {
      loading.value = false;
    });
};
defineExpose({
  show
});
</script>
